<?php

namespace App\Http\Controllers\Home;

use App\Models\Home\Address;
use App\Models\Home\Comment;
use App\Models\Home\Photo;
use App\Models\Home\User;
use App\Models\Home\UserInfo;
use App\Models\Home\Weibo;
use App\Models\RTresult;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    //用户个人中心页面
    public function edit(Request $request, $user_id)
    {
        $info = UserInfo::where('user_id', $user_id)->get()->first();
        //先将改用户的信息取出显示在页面上
        $details = User::join('user_infos', 'users.id', '=', 'user_infos.user_id')
            ->select('users.*', 'user_infos.*')
            ->where('users.id', '=', $user_id)
            ->get()->first()->toArray();
        $str = $details['address'];
        //第一次修改时用户地址id默认为空
        if (($str == '') || ($str == '0,0,0')) {
            $address = ['0', '0', '0'];
            $add = ['省份', '城市', '区县'];
        } else {
            $address = explode(',', $str);
            //获取每个地址id
            $pro = $address[0];
            $city = $address[1];
            $county = $address[2];
            //不能通过地址名称来查询id，因为地址名称有重名
            //地址查询
            $res = Address::select('name')->where('id', $pro)
                ->orWhere('id', $city)
                ->orWhere('id', $county)->get()->toArray();
            $add = array();
            $add[0] = $res[0]['name'];
            $add[1] = $res[1]['name'];
            $add[2] = $res[2]['name'];
        }
        return view('home/profile', ['info' => $info,
            'details' => $details, 'address' => $address,
            'add' => $add]);
    }

    //获取用户省份
    public function pro(Request $request)
    {
        $level = $request->level;
        //根据level查询省份
        $pros = Address::select('id', 'name')->where('level', $level)
            ->get();
        $rt_result = new RTresult();
        if ($pros) {
            $rt_result->status = true;
            $rt_result->message = $pros;
            return $rt_result->toJson();
        }
    }

    //用户城市
    public function city(Request $request)
    {
        $upid = $request->upid;
        //获取城市列表
        $cities = Address::select('id', 'name')->where('upid', $upid)
            ->get();
        //获取省会城市的城区默认显示在下拉列表第一栏
        $capital = Address::select('id', 'name')->where('upid', $cities[0]['id'])
            ->get();
//        dd($cities,$capital);
        $rt_result = new RTresult();
        if ($cities) {
            $rt_result->status = true;
            $rt_result->message = $cities;
            $rt_result->message1 = $capital;
            return $rt_result->toJson();
        }
    }

    //用户区县
    public function county(Request $request)
    {
        $upid = $request->upid;
        $counties = Address::select('id', 'name')->where('upid', $upid)
            ->get();
        $rt_result = new RTresult();
        if ($counties) {
            $rt_result->status = true;
            $rt_result->message = $counties;
            return $rt_result->toJson();
        }
    }

    //用户信息修改提交
    public function update(Request $request, $user_id)
    {
        if ($request->isMethod('post')) {
//            dd($request);
            //取出提交的数据
            $nickname = $request->nickname;
            $sex = $request->sex;
            $phone = $request->phone;
            $email = $request->email;
            //提交的地址是id号
            $pro = $request->pro;
            $city = $request->city;
            $county = $request->county;
            $arr = array($pro, $city, $county);
            $address = implode(',', $arr);
            //此时$address是用,分割的字符串
            //将数据update到数据表
            $res1 = User::where('id', $user_id)->update(
                ['phone' => $phone,
                    'email' => $email]);
            $res2 = UserInfo::where('user_id', $user_id)->update(
                ['nickname' => $nickname,
                    'sex' => $sex,
                    'address' => $address]);

            if ($res1 && $res2) {
                return redirect(url('/u/' . $user_id . '/edit'));
            }else{
                return redirect(url('/u/' . $user_id . '/edit'));
            };
        }
    }

    //用户修改密码
    public function password(Request $request, $user_id)
    {
        if ($request->isMethod('post')) {
            //进行格式验证
//          //设置格式验证规则
            $rules = ['old' => 'required',
                'password' => 'required|between:6,12|confirmed',
                'password_confirmation' => 'required'];
            //设置格式错误信息
            $msg = ['old.required' => '旧密码不能为空',
                'password.required' => '新密码不能为空',
                'password.between' => '密码必须在6-12位之间(含)',
                'password.confirmed' => '确认密码不正确',
                'password_confirmation.required' => '确认密码不能为空'];
            //进行格式验证
            $validator = Validator::make($request->all(), $rules, $msg);
            if ($validator->fails()) {
                return redirect('/u/' . $user_id . '/password')->withErrors($validator);
            } else {
//                echo "正在修改密码";
                //获取用户提交的密码
                $old = $request->old;
                $new = $request->password;
                //确认原密码是否正确
                $user = User::find($user_id);
                if (!Hash::check($old, $user->password)) {
                    return view('/home/password')->with('msg1', '原密码不正确！');
                } else {
                    //将新密码hash加密后录入系统
                    $user->password = Hash::make($new);
                    $user->save();
                    return view('/home/password')->with('msg2', '密码修改成功！');
                }
            }
        } else {
//        echo 'get请求';
            return view('home/password');
        }
    }

    //用户修改头像
    public function photo(Request $request, $user_id)
    {
        if ($request->isMethod('post')) {
            //进行格式验证
            //设置格式验证规则
            $rules = ['photo' => 'required|file|image|max:1048576'];
            //设置格式错误信息
            $msg = ['photo.required' => '图片不能为空',
                'photo.file' => '图片上传不成功',
                'photo.image' => '上传的不是图片',
                'photo.max' => '图片大小不能超过1MB'];
            //进行格式验证
            $validator = Validator::make($request->all(), $rules, $msg);
            if ($validator->fails()) {
                return back()->withErrors($validator);
            }
            //获取文件
            $photo = $request->file('photo');
            //获取文件名
//            $photoname = $photo->getClientOriginalName();
            //获取文件原始扩展名
            $photo_ex = $photo->getClientOriginalExtension();
            //文件后缀验证
            if (!in_array($photo_ex, array('jpg', 'gif', 'png', 'jpeg', 'JPG', 'GIF', 'PNG', 'JPEG'))) {
                return back()->with('photoFails', '图片格式仅限于jpg/gif/png/jpeg');
            }
            //验证通过,为图片创建一个新名字
            $newname = $user_id . date("Ymdhis") . '.' . $photo_ex;
            //存进public目录下的tmp目录等待处理，返回一个文件类型数据
            $tmp = $photo->move(public_path() . '/tmp', $newname);
            $path = public_path() . '/tmp/' . $newname;
            //对图片进行尺寸处理
            resize($path, 80, 80);
            $tmp->move(public_path() . '/images/avatar/', $newname);
            $newpath = '/images/avatar/' . $newname;
            $up = UserInfo::where('user_id', $user_id)
                ->update(
                    [
                        'avatar' => $newpath,
                    ]
                );
            //上传
            $rt_result = new RTresult();
            if ($up) {
                $rt_result->status = true;
                $rt_result->message = '上传成功';
                $rt_result->toJson();
                //将图片url取出传回视图
                $url = UserInfo::where('user_id', $user_id)->first()->avatar;
                Session::put('user.avatar', $url);
                return redirect('/u/' . Session::get('user.id'))->with('rt_result', $rt_result);
            } else {
                $rt_result->status = false;
                $rt_result->message = '上传失败';
                $rt_result->toJson();
                return redirect('/u/' . Session::get('user.id'))->with('rt_result', $rt_result);
            }
        }
        return view('home/photo');
    }

    //用户修改背景图片
    public function bgd(Request $request, $user_id)
    {
        if ($request->isMethod('post')) {
            //进行格式验证
            //设置格式验证规则
            $rules = ['bgd' => 'required|file|image|max:2097152'];
            //设置格式错误信息
            $msg = ['bgd.required' => '图片不能为空',
                'bgd.file' => '图片上传不成功',
                'bgd.image' => '上传的不是图片',
                'bgd.max' => '图片大小不能超过2MB'];
            //进行格式验证
            $validator = Validator::make($request->all(), $rules, $msg);
            if ($validator->fails()) {
                return back()->withErrors($validator);
            }
            //获取文件
            $bgd = $request->file('bgd');
            //获取文件名
//            $photoname = $photo->getClientOriginalName();
            //获取文件原始扩展名
            $bgd_ex = $bgd->getClientOriginalExtension();
            //文件后缀验证
            if (!in_array($bgd_ex, array('jpg', 'gif', 'png', 'jpeg', 'JPG', 'GIF', 'PNG', 'JPEG'))) {
                return back()->with('photoFails', '图片格式仅限于jpg/gif/png');
            }
            //验证通过,为图片创建一个新名字
            $newname = $user_id . date("Ymdhis") . '.' . $bgd_ex;
            //存进public目录下的images/background目录等待处理，返回一个文件类型数据
            $bgd->move(public_path() . '/images/background/', $newname);
            $newpath = '/images/background/' . $newname;
            //将背景图片url存入用户详情表
            $up = UserInfo::where('user_id', $user_id)
                ->update(
                    [
                        'bgd' => $newpath,
                    ]
                );
            //上传
            $rt_result = new RTresult();
            if ($up) {
                $rt_result->status = true;
                $rt_result->message = '上传成功';
                $rt_result->toJson();
                //将图片url取出传回视图
                $bgd = DB::table('user_infos')->where('user_id', $user_id)
                    ->first()->bgd;
                Session::put('user.bgd', $bgd);
                return redirect('/u/' . Session::get('user.id'))->with('rt_result', $rt_result);
            } else {
                $rt_result->status = false;
                $rt_result->message = '上传失败';
                $rt_result->toJson();
                return back()->with('rt_result', $rt_result);
            }
        }
        return view('home/background');
    }
}
